import Vue from 'vue'
import Vuex from 'vuex'
import service from './../utils/request'
import { message } from 'ant-design-vue'

import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)

import settleIn from './settleIn'
import user from './user'
// 不缓存到storage的数据
import unSave from './unSave'

export default new Vuex.Store({
  state: {
    // 面包屑数据
    breadcrumbData: []
  },
  mutations: {
    // 全局状态修改
    set_breadcurmb_data(state, data) {
      state.breadcrumbData = data;
    }
  },
  actions: {
    // 全局异步处理
    request(context, param) {
      let options = {...param};
      // 是否需要去除接口的同一错误提示
      const errorLogControl = options.errLog;
      delete options.errLog;
      // token设置
      options.headers = {};
      let tokenName = this.state.user.tokenName, tokenValue = this.state.user.tokenValue;
      if (tokenName && tokenValue && !param.unToken) {
        options.headers[tokenName] = tokenValue;
      }

      // 设置contentType
      if (param.contentType === 'form') {
        options.headers.contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
      }

      return new Promise((resolve, reject) => {
        service(options).then((data) => {
          if (data.success) {
            resolve(data)
          } else {
            reject(data);
            if(errorLogControl) return;
            message.error(data.message || '系统异常，请稍后重试');
          }
        }).catch((e) => {
          reject(e)
        })
      })
    }
  },
  modules: {
    settleIn,
    user,
    unSave
  },
  plugins: [createPersistedState({
    storage: window.localStorage,
    reducer(val) {
      let saveVal = JSON.parse(JSON.stringify(val));
      delete saveVal.unSave;
      return saveVal
    }
  })]
})
